import { customRef } from 'vue'

// 发布和订阅  eventBus emit / on  ==>  track / trigger
// track
// deps = []
// deps.push(()=>{...})

// trigger
// deps.forEach(fn=>fn())

export default function useDebouncedRef(value, delay = 300) {
  let timeout
  return customRef((track, trigger) => {
    return {
      get() {
        // 收集依赖
        track()
        return value
      },
      set(newValue) {
        clearTimeout(timeout)
        timeout = setTimeout(() => {
          value = newValue
          //
          trigger()
        }, delay)
      }
    }
  })
}
